package problem315;

//315.计算右侧小于当前元素的个数
//https://leetcode.cn/problems/count-of-smaller-numbers-after-self/

import java.util.ArrayList;
import java.util.List;

class Solution {
    int[] ret;
    int[] index;
    int[] tmpNums;
    int[] tmpIndex;
    public List<Integer> countSmaller(int[] nums) {
        int n = nums.length;
        ret = new int[n];
        index = new int[n];
        tmpNums = new int[n];
        tmpIndex = new int[n];

        for(int i = 0; i<n; i++) {
            index[i] = i;
        }
        mergeSort(nums, 0, n-1);
        
        List<Integer> list = new ArrayList<>();
        for(int x : ret) {
            list.add(x);
        }
        return list;
    }
    public void mergeSort(int[] nums, int left, int right) {
        if(left >= right) return;
        int mid = left + (right-left)/2;
        mergeSort(nums, left, mid);
        mergeSort(nums, mid+1, right);

        //[left, mid] [mid+1, right]
        int cur1 = left, cur2 = mid+1, i = 0;
        while(cur1 <= mid && cur2 <= right) {
            if(nums[cur1] <= nums[cur2]) {
                tmpIndex[i] = index[cur2];
                tmpNums[i++] = nums[cur2++];
            }else {
                ret[index[cur1]] += right-cur2+1;
                tmpIndex[i] = index[cur1];
                tmpNums[i++] = nums[cur1++];
            }
        }
        while(cur1 <= mid) {
            tmpIndex[i] = index[cur1];
            tmpNums[i++] = nums[cur1++];
        }
        while(cur2 <= right) {
            tmpIndex[i] = index[cur2];
            tmpNums[i++] = nums[cur2++];
        }

        for(int j = left; j<=right; j++) {
            nums[j] = tmpNums[j-left];
            index[j] = tmpIndex[j-left];
        }
    }
}